package DBUtil;

import java.io.NotSerializableException;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import entity.Course;
import entity.User;

public class DBUtils <T> {
	
	// 插入工具
	public static int commInsert(String sql,Object...param) {
		
		// 获取连接
		Connection connection = DBManager.getConnection();
		if(connection==null) System.out.println("连接不成功");
        else System.out.println("成功连接");
		PreparedStatement pstmt = null;
		// 获取处理对象
		try {
			 pstmt = connection.prepareStatement(sql);
			 // 给占位符赋值
			 for(int i=0;i<param.length;i++) {
				 pstmt.setObject(i+1, param[i]);
			 }
			 
			 // 返回结果集
			 return  pstmt.executeUpdate();
			 
			 
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DBManager.close(pstmt,connection);
		}
		return 0;
	}
	
	// 查询工具
	
	public  List<T> commSelect(String sql ,Object... param) throws InstantiationException, IllegalAccessException,NotSerializableException{
		
		List<T> list = new ArrayList<>();
		// 获取连接对象
		Connection connection = DBManager.getConnection();
		PreparedStatement pstmt = null;
		ResultSet reslut = null;
		try {
		
			// 获取处理对象
			 pstmt = connection.prepareStatement(sql);
			 
			// 给占位符赋值
			 if(param!=null) {
				 for(int i=0;i<param.length;i++) {
						pstmt.setObject(i+1,param[i]);
					}
			 }
			 reslut = pstmt.executeQuery();

			
			 while(reslut.next()) {
				
				 Course course = new Course();
				 Class<Course > class1 = (Class<Course>) course.getClass();
				 
				 Field[] Fields = class1.getDeclaredFields();
				 
				 for (Field  field : Fields) {
					 
					 field.setAccessible(true);
					 String name = field.getName();
					 
					 Object value = reslut.getObject(name);
					 field.set(course, value);
				}
				 list.add( (T) course);
			 }
			 return list;
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DBManager.close(reslut,pstmt,connection);
		}
		return null;
	}
	
	// 登录验证工具
	public int login(String sql , Object ...param) {
		
		Connection connection = DBManager.getConnection();
		PreparedStatement pstmt = null;
		ResultSet result = null;
		int flag = -1;
		try {
			 pstmt = connection.prepareStatement(sql);
			 if(param !=null) {
				 for(int i=0;i<param.length;i++) {
					 pstmt.setObject(i+1, param[i]);
				 }
			 }
			 
			 result = pstmt.executeQuery();
			 if(result.next()) {
				flag = result.getInt(1);
			 }
			 if(flag >0) {
				 return 1;
			 }else {
				 return 0;// 账户密码错误
			 }
			
		} catch (SQLException e) {
			e.printStackTrace();
			return -1; // 系统异常
		}finally {
			DBManager.close(result,pstmt,connection);
		}
		
	}
}
